'use strict'

const Controller = require('egg').Controller

const UserMessageModel = require('../../models/user_message')

const trajectory_table = require('../../models/trajectory_table')

const { Op } = require('sequelize')

const dayjs = require('dayjs')

class UserMessageController extends Controller {
  userMessageModel = UserMessageModel(this.app.model)
  //轨迹数据
  trajectoryTable = trajectory_table(this.app.model)

  async queryAll() {
    const { ctx } = this
    try {
      const user_id = ctx.userId
      const { startDate, endDate, equipmentId: equipment_id } = ctx.query
      const where = {
        del_flag: '0',
        user_id,
      }
      equipment_id && (where.equipment_id = equipment_id)
      if (startDate && endDate) {
        where.sending_time = {
          [Op.between]: [startDate, endDate],
        }
      }
      const result = await this.userMessageModel.findAll({
        where,
        order: [['sending_time', 'DESC']],
      })
      ctx.success('查询成功', result)
    } catch (error) {
      ctx.failure('查询失败', error)
    }
  }

  async query() {
    const { ctx } = this
    try {
      const user_id = ctx.userId
      const { id } = ctx.query
      if (!id) {
        return ctx.failure('请输入查询ID')
      }
      const where = {
        del_flag: '0',
        user_id,
        id,
      }
      const results = await this.userMessageModel.findOne({ where })
      if (results) {
        const { sending_time, equipment_id } = results
        const startDate = dayjs(sending_time)
          .subtract(10, 'minute')
          .format('YYYY-MM-DD HH:mm:ss')
        const endDate = dayjs(sending_time).format('YYYY-MM-DD HH:mm:ss')
        const result = await this.trajectoryTable.findAll({
          where: {
            equipment_id,
            submit_date: {
              [Op.between]: [startDate, endDate],
            },
          },
        })
        ctx.success('查询成功', result)
      } else {
        ctx.success('未查询到id', results)
      }
    } catch (error) {
      ctx.failure('查询失败', error)
    }
  }

  async delete() {
    const { ctx } = this
    try {
      const { equipmentId: equipment_id } = ctx.query
      const user_id = ctx.userId
      const where = { user_id, equipment_id }
      const result = await this.userMessageModel.update(
        { del_flag: '1' },
        { where }
      )
      if (result) {
        ctx.success('解绑成功', result)
      } else {
        ctx.success('解绑失败：未查询到设备ID')
      }
    } catch (error) {
      ctx.failure('解绑失败', error)
    }
  }
}

module.exports = UserMessageController
